<?php

namespace app\common\service;


use app\model\FreshAgentAward;
use app\model\FreshUserAward;
use app\util\Tools;
use think\Cache;
use think\Db;

class Settle{



    /**
     * 佣金记录生成
     * @param $type 1订单 2充值 3年卡 4拼团
     * @param $order
     * @return bool
     */
    public static function settleSubmit($type, $order, $isToAccount){
        if($order['profitTotal'] == 0) return true;
        $programModel = new \app\model\UserProgram();
        $user_program = $programModel->where('userID',$order['userID'])->find();
        if($user_program['referID']){   //推荐人
            $num = 0;
            $referer_tree = [];
            $vip_tree = [];
            $user_list = Settle::getRefererTree($order['userID'], 0, 0,  $referer_tree, true, $vip_tree, 0);
//           return $user_list;
            $key_arr = [];
            $rate_settled = 0;
            $config = config('settle.reward');
            foreach ($user_list as $k => $v){
                if(in_array($v['freshLevel'], [1,2]) && !in_array($v['freshLevel'], $key_arr)){ //会员奖励
                    if($v['freshLevel'] == 1){
                        //直推奖
                        if($rate_settled<$config['L_1']){
                            self::referReward($v, $order, $type, $rate_settled, $isToAccount);
                            $rate_settled = $config['L_1'];
                            $key_arr[] = 1;
                        }

                    }else{
                        //间推奖
                        if($rate_settled<$config['L_2']){
                            self::indirectReward($v, $order, $type, $rate_settled, $isToAccount);
                            $key_arr[] = 2;
                            $rate_settled = $config['L_2'];
                        }
                    }
                }
                if($v['isPromoter'] == 1){
                    if($rate_settled<$v['promoterRate']){
                        self::promoterReward($v, $order, $type, $rate_settled, $isToAccount); //业务员奖励
                        $rate_settled = $v['promoterRate'];
                    }
                    $agent = Db::name('fresh_agent')->where([
                        'status' => 1,
                        'agentID' => $v['freshAgentID']
                    ])->find();
                    if(isset($agent['agentID']) &&$rate_settled<$config['A_'.$agent['type']]){
                        self::agentReward($v, $order, $type, $rate_settled, $agent, $isToAccount); //代理商奖励
                        $rate_settled = $config['A_'.$agent['type']];
                    }
                    break;
                }
            }
        }else{
            return  true;
        }
        return true;
    }

    //发放直推奖 1订单 2充值 3年卡 4拼团
    public static function referReward($user, $order, $type, $rate_settled, $isToAccount){
        $config = config('settle.reward');
        $rate = $config['L_1'];
        if($rate_settled>=$rate) return true;
        $radio = Tools::bcCalculate($rate, $rate_settled, '-');
        if($radio > 0){
            $money = Tools::bcCalculate($order['profitTotal'], $radio, '*');
            $remark = "获得{$money}元直推奖";
            self::insertReward($user['userID'], $radio, $money, 1, $order['userID'], $order['orderID'], $type,$remark, $isToAccount);
        }
    }

    //发放间推奖 1订单 2充值 3年卡 4拼团
    public static function indirectReward($user, $order, $type, $rate_settled, $isToAccount){
        $config = config('settle.reward');
        $rate = $config['L_2'];
        if($rate_settled>=$rate) return true;
        $radio = Tools::bcCalculate($rate, $rate_settled, '-');
        if($radio > 0){
            $money = Tools::bcCalculate($order['profitTotal'], $radio, '*');
            $remark = "获得{$money}元间推奖";
            self::insertReward($user['userID'], $radio, $money, 2, $order['userID'], $order['orderID'], $type,$remark, $isToAccount);
        }
        ;
    }

    //业务员直推奖
    public static function promoterReward($user, $order, $type, $rate_settled, $isToAccount){
        $rate = $user['promoterRate'];
        if($rate_settled>=$rate) return true;
        $radio = Tools::bcCalculate($rate, $rate_settled, '-');
        if($radio > 0){
            $money = Tools::bcCalculate($order['profitTotal'], $radio, '*');
            $remark = "获得{$money}元业务员推广奖";
            self::insertReward($user['userID'], $radio, $money, 3, $order['userID'], $order['orderID'], $type,$remark, $isToAccount);
        }
    }

    //服务站奖励
    public static function agentReward($user, $order, $type, $rate_settled, $agent, $isToAccount){
        $config = config('settle.reward');
        $rate = $config['A_'.$agent['type']];
        if($rate_settled>=$rate) return true;
        $radio = Tools::bcCalculate($rate, $rate_settled, '-');
        if($radio > 0){
            $money = Tools::bcCalculate($order['profitTotal'], $radio, '*');
            $remark = "获得{$money}元直推奖";
            self::insertAgentReward($agent, $radio, $money, $type, $order['userID'], $order['orderID'],$remark, $isToAccount);
        }
    }

    public static function insertReward($userID, $radio, $money, $type, $sourceUserID, $orderID,$orderSoruce, $remark,$isToAccount){

        $add = [
            'userID' => $userID,
            'radio' => $radio,
            'money' => $money,
            'type' => $type,
            'status' => $isToAccount,
            'sourceUserID' => $sourceUserID,
            'orderID' => $orderID,
            'orderSoruce' => $orderSoruce,
            'addTime' => time(),
            'addDate' => date('Ymd'),
            'payDate' => date('Ymd'),
            'month' => date('Ym'),
            'remark' => $remark,
        ];
        $flag = FreshUserAward::create($add);
        if(!$flag) throw new \Exception("佣金结算失败-1");
        if($isToAccount == 1) self::changeMoney($userID, $money, $remark, $flag, 1); //发放奖励
    }


    public static function insertAgentReward($agent, $radio, $money, $type, $sourceUserID, $orderID, $remark,$isToAccount){

        $add = [
            'agentID' => $agent['agentID'],
            'money' => $money,
            'radio' => $radio,
            'type' => $type,
            'status' => $isToAccount,
            'sourceUserID' => $sourceUserID,
            'relateID' => $orderID,
            'addTime' => time(),
            'addDate' => date('Ymd'),
            'payDate' => date('Ymd'),
            'month' => date('Ym'),
            'areaID' => $agent['areaID'],
            'remark' => $remark,
        ];

        $flag = FreshAgentAward::create($add);
        if(!$flag) throw new \Exception("佣金结算失败-1");
        if($isToAccount == 1) AgentSettle::changeMoney($agent['agentID'], $money, $remark, $flag); //发放奖励
    }
    /**
     * 佣金发放
     * @param $userID
     * @param $money
     * @param $remark
     * @param $userAwardId
     * @throws \think\exception\DbException
     */
    public static function changeMoney($userID, $money, $remark, $userAwardId, $source){
        $userProgram = \app\model\UserProgram::get(['userID' => $userID]);
        $freshMoney = $userProgram->freshMoney + $money;
        $userProgram->freshMoney = $freshMoney;
        $resUserProgram = $userProgram->save();
        //添加记录进流水表
        $moneylog = [
            "userID" => $userID,
            "money" => $money,
            "balance" => $freshMoney,
            "type" => 1,
            "turnover" => 1,
            "content" => $remark,
            "addTime" => time(),
            "orderSoruce" => 1,
            "source" => $source,
            "relateID" => $userAwardId,
        ];
        $resMoneyLog = \app\model\FreshUserMoneyLog::create($moneylog);
        if(!$resMoneyLog || !$resUserProgram){
            throw new \Exception("佣金结算失败-2");
        }
    }


    //获取推荐人tree
    public static function getRefererTree($userID, $count = 0, $manage_level = 0, &$referer_tree = [], $is_first = true, &$vip_tree = [], $num = 0)
    {
        $programModel = new \app\model\UserProgram();
        static $current_level = 0;
        static $tree_ids = [];
        if ($is_first) {
            $current_level = 0;
            $tree_ids = [];
        }

        if (!$userID) {
            return $referer_tree;
        }

        $user = $programModel->where(['userID' => $userID])->find();
        if ($user['referID']) {
            $referer = $programModel->where(['userID' => $user['referID']])->find();
            $referer_tree[] = $referer;

            if($referer['freshLevel']>0) $vip_tree[] = $referer;
            if($num && count($vip_tree)==$num) return $referer_tree;

            if (isset($tree_ids[$referer['userID']])) {
                throw new \Exception("关系树死循环");
            }
            $tree_ids[$referer['userID']] = $referer['userID'];

            //级数控制
            $current_level++;
            if ($count && $current_level == $count) {
                return $referer_tree;
            }

            //管理级别控制
            if ($manage_level && $manage_level == $referer['vip_level']) {
                return $referer_tree;
            }

            if($referer['isPromoter'] == 1) {
                return $referer_tree;
            }

            self::getRefererTree($referer['userID'], $count, $manage_level, $referer_tree, $is_first = false, $vip_tree, $num);
        }

        return $referer_tree;
    }



}


?>
